package cn.school.common.valid;

import cn.school.annotation.ExcelIntValid;
import cn.school.annotation.ExcelStrLengthValid;
import cn.school.annotation.ExcelValid;
import cn.school.common.exception.ApiException;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Objects;

public class ExcelInValid {

    /**
     * Excel导入字段校验
     *
     * @param object 校验的JavaBean 其属性须有自定义注解
     * @author linmaosheng
     */
    public static void valid(Object object) {
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //属性的值
            Object fieldValue = null;
            try {
                fieldValue = field.get(object);
            } catch (IllegalAccessException e) {
                //BusinessException是我自定义的异常，这里需要改成你自己写的自定义异常
                throw new ApiException("数据异常，请检查导入数据是否正确", 500);
            }

            //是否包含必填校验注解
            boolean isExcelValid = field.isAnnotationPresent(ExcelValid.class);
            if (isExcelValid && Objects.isNull(fieldValue)) {
                throw new ApiException(field.getAnnotation(ExcelValid.class).message(), 500);
            }
            //是否包含字符串长度校验注解
            boolean isExcelStrValid = field.isAnnotationPresent(ExcelStrLengthValid.class);
            if (isExcelStrValid) {
                String cellStr = fieldValue.toString();
                int length = field.getAnnotation(ExcelStrLengthValid.class).length();
                if (StringUtils.isNotBlank(cellStr) && cellStr.length() > length) {
                    throw new ApiException(field.getAnnotation(ExcelStrLengthValid.class).message(), 500);
                }
            }
            //是否包含int类型校验注解
            boolean isExcelIntValid = field.isAnnotationPresent(ExcelIntValid.class);
            if (isExcelIntValid) {
                if (fieldValue instanceof Integer) {
                    int cellInt = Integer.parseInt(fieldValue.toString());
                    int min = field.getAnnotation(ExcelIntValid.class).min();
                    int max = field.getAnnotation(ExcelIntValid.class).max();
                    if (cellInt < min || cellInt > max) {
                        throw new ApiException(field.getAnnotation(ExcelIntValid.class).message(), 500);
                    }
                }
            }

        }
    }


}
